/**
 * 小程序状态管理工具
 * 提供类似Pinia的状态管理功能
 */

// 获取应用实例的辅助函数
const getAppInstance = () => {
  return getApp()
}

/**
 * 用户状态管理
 */
const userStore = {
  // 获取用户信息
  getUserInfo() {
    const app = getAppInstance()
    return app.globalData.userInfo
  },

  // 获取token
  getToken() {
    const app = getAppInstance()
    return app.globalData.token
  },

  // 检查是否已登录
  isLoggedIn() {
    const app = getAppInstance()
    return app.globalData.userInfo.isLoggedIn
  },

  // 检查是否有管理员权限
  hasAdminPermission() {
    const app = getAppInstance()
    return app.hasAdminPermission()
  },

  // 检查是否已认证
  isAuthenticated() {
    const app = getAppInstance()
    return app.isAuthenticated()
  },

  // 设置用户信息
  setUserInfo(userInfo, token) {
    const app = getAppInstance()
    app.setUserInfo(userInfo, token)
  },

  // 更新用户信息
  updateUserInfo(updates) {
    const app = getAppInstance()
    app.updateUserInfo(updates)
  },

  // 清除用户信息
  clearUserInfo() {
    const app = getAppInstance()
    app.clearUserInfo()
  },

  // 登录
  async login(loginData) {
    const { userApi } = require('./api')
    try {
      const result = await userApi.login(loginData)
      console.log('登录API返回完整数据:', result)

      if (result.code === 200 && result.data) {
        const userData = result.data
        console.log('解析用户数据:', userData)

        // 根据后端返回的数据结构构建用户信息
        const userInfo = {
          isLoggedIn: true,
          nickname: userData.nickname || userData.username || '',
          avatar: userData.avatar || '/images/NY_RectangularFavicon.png',
          description: '欢迎回来！',
          username: userData.username || '',
          permissions: userData.permissions || []
        }

        const token = userData.token || ''
        console.log('准备保存的用户信息:', userInfo)
        console.log('准备保存的token:', token)

        // 保存用户信息和token
        this.setUserInfo(userInfo, token)

        // 登录成功后合并收藏数据
        setTimeout(async () => {
          try {
            await favoritesStore.mergeLocalFavoritesOnLogin()
          } catch (error) {
            console.error('合并收藏数据失败:', error)
          }
        }, 100)

        return result
      } else {
        throw new Error(result.msg || result.message || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  },

  // 登出
  async logout() {
    const { userApi } = require('./api')
    try {
      await userApi.logout()
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      this.clearUserInfo()
    }
  }
}

/**
 * 收藏状态管理
 */
const favoritesStore = {
  // 获取收藏列表
  getFavorites() {
    const app = getAppInstance()
    return app.globalData.favorites
  },

  // 获取收藏数量
  getFavoriteCount() {
    const app = getAppInstance()
    return app.globalData.favorites.length
  },

  // 检查是否已收藏
  isFavorited(newsId) {
    const app = getAppInstance()
    return app.globalData.favorites.some(function(item) {
      return item.news_id === newsId || item.id === newsId
    })
  },

  // 添加收藏
  async addFavorite(article) {
    const app = getAppInstance()
    app.addFavorite(article)

    // 如果用户已登录，同步到服务器
    if (userStore.isLoggedIn()) {
      try {
        const userDataSyncApi = require('./userDataSyncApi')
        const favoriteData = [{
          newsId: article.news_id || article.newsId || article.id,
          title: article.title,
          url: article.url || `/news/${article.news_id || article.newsId || article.id}`,
          category: article.category,
          section: article.section,
          favoriteTime: new Date().toISOString()
        }]

        const result = await userDataSyncApi.uploadFavorites(favoriteData, {
          overwriteConflicts: true
        })

        if (result.code === 200 && result.data.success) {
          console.log('收藏同步成功:', result.data)
        }
      } catch (error) {
        console.error('收藏同步失败:', error)
        // 同步失败不影响本地收藏
      }
    }
  },

  // 移除收藏
  async removeFavorite(newsId) {
    const app = getAppInstance()
    app.removeFavorite(newsId)

    // 如果用户已登录，从服务器删除
    if (userStore.isLoggedIn()) {
      try {
        const userDataSyncApi = require('./userDataSyncApi')
        const result = await userDataSyncApi.deleteFavorite(newsId)

        if (result.code === 200 && result.data.success) {
          console.log('取消收藏同步成功:', result.data)
        }
      } catch (error) {
        console.error('取消收藏同步失败:', error)
        // 同步失败不影响本地操作
      }
    }
  },

  // 切换收藏状态
  toggleFavorite(article) {
    if (this.isFavorited(article.news_id || article.id)) {
      this.removeFavorite(article.news_id || article.id)
      return false
    } else {
      this.addFavorite(article)
      return true
    }
  },

  // 清空收藏
  clearFavorites() {
    const app = getAppInstance()
    app.globalData.favorites = []
    try {
      wx.removeStorageSync('favorites')
    } catch (error) {
      console.error('清空收藏失败:', error)
    }
  },

  // 从服务器下载收藏数据
  async downloadServerFavorites() {
    if (!userStore.isLoggedIn()) {
      console.log('用户未登录，跳过下载收藏数据')
      return []
    }

    try {
      const userDataSyncApi = require('./userDataSyncApi')
      console.log('从服务器下载收藏数据')
      const result = await userDataSyncApi.downloadUserData(['favorite'])

      if (result.code === 200 && result.data.success) {
        const serverFavorites = result.data.downloadData || []
        console.log(`从服务器下载了 ${serverFavorites.length} 条收藏数据`)

        // 转换为本地格式
        const localFavorites = serverFavorites.map(item => ({
          news_id: item.newsId,
          newsId: item.newsId,
          id: item.newsId,
          title: item.newsTitle,
          url: item.newsUrl,
          category: item.newsCategory,
          section: item.newsSection,
          createTime: item.createTime,
          favoriteTime: item.extraData?.favoriteTime || item.createTime
        }))

        // 更新本地收藏列表
        const app = getAppInstance()
        app.globalData.favorites = localFavorites

        // 保存到本地存储
        try {
          wx.setStorageSync('favorites', localFavorites)
        } catch (error) {
          console.error('保存收藏数据失败:', error)
        }

        return localFavorites
      }
    } catch (error) {
      console.error('从服务器下载收藏数据失败:', error)
    }
    return []
  },

  // 合并本地和服务器收藏数据（登录时调用）
  async mergeLocalFavoritesOnLogin() {
    try {
      console.log('登录后合并收藏数据')
      const app = getAppInstance()
      const localFavorites = app.globalData.favorites || []

      // 获取服务器收藏数据
      const serverFavorites = await this.downloadServerFavorites()

      // 合并去重（以newsId为准）
      const mergedFavorites = []
      const seenIds = new Set()

      // 先添加服务器数据
      serverFavorites.forEach(item => {
        const newsId = item.news_id || item.newsId || item.id
        if (newsId && !seenIds.has(newsId)) {
          seenIds.add(newsId)
          mergedFavorites.push(item)
        }
      })

      // 再添加本地独有数据
      localFavorites.forEach(item => {
        const newsId = item.news_id || item.newsId || item.id
        if (newsId && !seenIds.has(newsId)) {
          seenIds.add(newsId)
          mergedFavorites.push(item)
        }
      })

      console.log(`合并后共 ${mergedFavorites.length} 条收藏`)

      // 更新本地数据
      app.globalData.favorites = mergedFavorites
      try {
        wx.setStorageSync('favorites', mergedFavorites)
      } catch (error) {
        console.error('保存合并后的收藏数据失败:', error)
      }

      // 如果有新的本地收藏需要上传到服务器
      const newLocalFavorites = localFavorites.filter(local => {
        const localId = local.news_id || local.newsId || local.id
        return !serverFavorites.some(server => {
          const serverId = server.news_id || server.newsId || server.id
          return serverId === localId
        })
      })

      if (newLocalFavorites.length > 0) {
        console.log(`需要上传 ${newLocalFavorites.length} 条新的本地收藏到服务器`)
        await this.uploadLocalFavoritesToServer(newLocalFavorites)
      }

    } catch (error) {
      console.error('合并收藏数据失败:', error)
    }
  },

  // 上传本地收藏到服务器
  async uploadLocalFavoritesToServer(favorites) {
    try {
      if (!favorites || favorites.length === 0) return
      if (!userStore.isLoggedIn()) {
        console.log('用户未登录，跳过上传收藏数据')
        return
      }

      const userDataSyncApi = require('./userDataSyncApi')
      console.log(`准备上传 ${favorites.length} 条收藏到服务器`)

      const favoriteDataList = favorites.map(item => ({
        newsId: item.news_id || item.newsId || item.id,
        title: item.title,
        url: item.url || `/news/${item.news_id || item.newsId || item.id}`,
        category: item.category,
        section: item.section,
        favoriteTime: item.favoriteTime || item.createTime || new Date().toISOString()
      }))

      const result = await userDataSyncApi.uploadFavorites(favoriteDataList, {
        overwriteConflicts: false // 不覆盖已存在的收藏
      })

      if (result.code === 200 && result.data.success) {
        console.log(`成功上传 ${favoriteDataList.length} 条收藏到服务器`)
      } else {
        throw new Error(result.data?.errorMessage || '上传失败')
      }
    } catch (error) {
      console.error('上传收藏到服务器失败:', error)
    }
  }
}

/**
 * 历史记录状态管理
 */
const historyStore = {
  // 获取历史记录
  getHistory() {
    const app = getAppInstance()
    return app.globalData.history
  },

  // 获取历史记录数量
  getHistoryCount() {
    const app = getAppInstance()
    return app.globalData.history.length
  },

  // 添加历史记录
  addHistory(article) {
    const app = getAppInstance()
    app.addHistory(article)
  },

  // 清空历史记录
  clearHistory() {
    const app = getAppInstance()
    app.clearHistory()
  },

  // 获取最近浏览记录
  getRecentHistory(count = 10) {
    const app = getAppInstance()
    return app.globalData.history.slice(0, count)
  }
}

/**
 * 新闻状态管理
 */
const newsStore = {
  // 获取新闻数据
  getNewsData() {
    const app = getAppInstance()
    return app.globalData.newsData
  },

  // 获取首页新闻
  getHomeNews() {
    const app = getAppInstance()
    return app.globalData.newsData.homeNews
  },

  // 获取搜索结果
  getSearchResults() {
    const app = getAppInstance()
    return app.globalData.newsData.searchResults
  },

  // 获取分类列表
  getCategories() {
    const app = getAppInstance()
    return app.globalData.newsData.categories
  },

  // 获取学院列表
  getSections() {
    const app = getAppInstance()
    return app.globalData.newsData.sections
  },

  // 设置新闻数据
  setNewsData(key, data) {
    const app = getAppInstance()
    app.setNewsData(key, data)
  },

  // 添加新闻到列表
  addNewsToList(newsList, append = false) {
    const app = getAppInstance()
    app.addNewsToList(newsList, append)
  },

  // 设置搜索结果
  setSearchResults(results, append = false) {
    const app = getAppInstance()
    app.setSearchResults(results, append)
  },

  // 设置分类数据
  setCategories(categories) {
    const app = getAppInstance()
    app.setCategories(categories)
  },

  // 设置学院数据
  setSections(sections) {
    const app = getAppInstance()
    app.setSections(sections)
  },

  // 设置搜索参数
  setSearchParams(params) {
    const app = getAppInstance()
    app.setSearchParams(params)
  },

  // 设置分页信息
  setPagination(currentPage, totalPages, hasMore) {
    const app = getAppInstance()
    app.setPagination(currentPage, totalPages, hasMore)
  }
}

/**
 * 应用状态管理
 */
const appStore = {
  // 获取应用状态
  getAppState() {
    const app = getAppInstance()
    return app.globalData.appState
  },

  // 获取网络状态
  getNetworkStatus() {
    const app = getAppInstance()
    return app.globalData.appState.networkStatus
  },

  // 检查是否在线
  isOnline() {
    const app = getAppInstance()
    return app.globalData.appState.networkStatus === 'online'
  },

  // 检查是否离线
  isOffline() {
    const app = getAppInstance()
    return app.globalData.appState.networkStatus === 'offline'
  },

  // 获取主题
  getTheme() {
    const app = getAppInstance()
    return app.globalData.appState.theme
  },

  // 检查是否为深色主题
  isDarkTheme() {
    const app = getAppInstance()
    return app.globalData.appState.theme === 'dark'
  },

  // 设置应用状态
  setAppState(key, value) {
    const app = getAppInstance()
    app.setAppState(key, value)
  },

  // 设置加载状态
  setLoading(loading) {
    const app = getAppInstance()
    app.setLoading(loading)
  },

  // 设置全局加载状态
  setGlobalLoading(loading) {
    const app = getAppInstance()
    app.setGlobalLoading(loading)
  },

  // 设置主题
  setTheme(theme) {
    const app = getAppInstance()
    app.setTheme(theme)
  },

  // 切换主题
  toggleTheme() {
    const app = getAppInstance()
    app.toggleTheme()
  },

  // 设置调试模式
  setDebugMode(debug) {
    const app = getAppInstance()
    app.setDebugMode(debug)
  }
}

module.exports = {
  userStore,
  favoritesStore,
  historyStore,
  newsStore,
  appStore
}
